const router = require("koa-router")()
const { getList, create, update, del } = require("../controller/comment")
const loginCheck = require("../middleware/loginCheck")

router.prefix("/comment")

/**
 * @description: 提交评论信息
 */
router.get("/list", loginCheck, async (ctx, next) => {
  // 获取 filterType：1 - 全部；2 - 自己
  let { filterType } = ctx.query
  filterType = parseInt(filterType) || 1
  // 获取当前用户名
  let username = ""

  if (filterType === 2) {
    username = ctx.session.userInfo.username
  }
  const list = await getList(username)
  ctx.body = {
    errno: 0,
    data: list
  }
})

/**
 * @description: 提交评论信息
 */
router.post("/create", loginCheck, async (ctx, next) => {
  try {
    const { content } = ctx.request.body
    const { username } = ctx.session.userInfo

    const newComment = await create(content, username)
    // 返回
    ctx.body = {
      errno: 0,
      data: newComment
    }
  } catch (error) {
    console.error("创建留言失败", error)
    ctx.body = {
      errno: -1,
      message: "创建留言失败"
    }
  }
})

/**
 * @description: 编辑评论信息
 */
router.post("/update", loginCheck, async (ctx, next) => {
  try {
    const { _id, content } = ctx.request.body
    const { username } = ctx.session.userInfo

    const newComment = await update(_id, content, username)
    // 返回
    ctx.body = {
      errno: 0,
      data: newComment
    }
  } catch (error) {
    console.error("编辑留言失败", error)
    ctx.body = {
      errno: -1,
      message: "编辑留言失败"
    }
  }
})
/**
 * @description: 删除评论信息
 */
router.post("/del", loginCheck, async (ctx, next) => {
  const { _id } = ctx.request.body
  const { username } = ctx.session.userInfo
  try {
    await del(_id, username)
    // 返回
    ctx.body = {
      errno: 0
    }
  } catch (error) {
    console.error("删除失败", error)
    ctx.body = {
      errno: -1,
      message: "删除失败"
    }
  }
})

module.exports = router
